package util

import groovy.xml.MarkupBuilder

/**
 * converts the given CSV file to an xml file
 */
class CSVtoXML {

    /**
     * simple main method
     * @param args
     */
    static void main(String[] args) {

        if (args.length != 2) {
            println "Usage:\n"
            println "arg[0] = file name"
            println "arg[1] = output directory"
            println ""
            System.exit(-1)
        }

        File data = new File(args[0])

        boolean columnComplete = false

        def experiments = [:]
        data.text.eachLine({ String line ->

            line = line.trim()
            List content = line.split("\t").toList()

            if (content.size() == 8) {

                //check for first line
                if (!columnComplete) {
                    columnComplete = (
                    content[0].trim() == "exp ID" &&
                            content[1].trim() == "class ID" &&
                            content[2].trim() == "sample ID" &&
                            content[3].trim() == "sample name" &&
                            content[4].trim() == "file name" &&
                            content[5].trim() == "species" &&
                            content[6].trim() == "tissue" &&
                            content[7].trim() == "Treatment"
                    )

                    if (!columnComplete) {
                        println "the file is invalid, some of the columns where missing or out of order"

                        content.eachWithIndex {String column, int index ->
                            println "column[${index}] = ${column}"
                        }
                        System.exit(-3)

                    }
                }
                //build the experiment maps
                else {
                    if (experiments[content[0]] == null) {
                        experiments[content[0]] = [:]
                        experiments[content[0]].classes = [:]
                    }

                    if (experiments[content[0]].classes[content[1]] == null) {
                        experiments[content[0]].classes[content[1]] = [:]

                        experiments[content[0]].classes[content[1]].samples = []
                        experiments[content[0]].classes[content[1]].species = content[5]
                        experiments[content[0]].classes[content[1]].tissue = content[6]
                        experiments[content[0]].classes[content[1]].treatment = content[7]
                        experiments[content[0]].classes[content[1]].id = content[1]

                    }

                    experiments[content[0]].classes[content[1]].samples.add([
                            sampleName: content[3],
                            fileName: content[4].replaceAll(":","_"),
                            sampleId: content[2]
                    ])


                }


            } else {
                println "the file is invalid, it needs 8 columns!, but it has ${content.size()}"

                content.eachWithIndex {String column, int index ->
                    println "column[${index}] = ${column}"
                }

                System.exit(-2)
            }
        })

        //transforming our experiments to a couple of xml files
        experiments.keySet().each {String key ->

            def out = new StringWriter()
            MarkupBuilder xml = new MarkupBuilder(out);

            xml.experiment(id: "${key}", title: "${key}") {

                classes {

                    def classes = experiments[key].classes

                    classes.keySet().each {def clazzKey ->
                        def clazz = classes[clazzKey]

                        "class"(id: clazz.id, species: clazz.species, organ: clazz.tissue, tissue: clazz.tissue, treatment: clazz.treatment) {

                            def samplesData = clazz.samples

                            samples {
                                samplesData.each {Map sampleMap ->
                                    sample(id: sampleMap.sampleId, fileName: sampleMap.fileName, label: sampleMap.sampleName) {}
                                }
                            }

                        }
                    }

                }
            }

            new File(args[1],"${key}.xml").write(out.toString())
        }
    }
}
